package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;
import com.zzyl.common.utils.CodeGenerator;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto
     * @return
     */
    @Override
    @Transactional
    public int apply(CheckInApplyDto checkInApplyDto) {
        // 判断老人是否已入住
        // 通过身份证号查询老人
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
        elderQueryWrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo());
        elderQueryWrapper.eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(elderQueryWrapper);
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new BaseException("该老人已入住");
        }
        // 2.更新床位状态为已入住
        // 获取申请者在申请配置表中填写的床位id
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        // 3.新增或更新老人信息
        elder = saveOrUpdateElder(checkInApplyDto, bed);

        // 4. 新增签约办理,插入合同表
        saveContract(checkInApplyDto, elder);
        // 5. 新增入住信息
        CheckIn checkIn = saveCheckIn(checkInApplyDto, elder);
        // 6. 新增入住配置
        saveCheckInConfig(checkIn, checkInApplyDto);

        return 0;
    }



    /**
     * 第四个私有方法,新增入住配置
     *
     * @param checkIn
     * @param checkInApplyDto
     */
    private void saveCheckInConfig(CheckIn checkIn, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        System.out.println("feeStartDate:" + checkInApplyDto.getCheckInConfigDto().getFeeStartDate());
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 第三个私有方法,新增入住信息
     *
     * @param checkInApplyDto
     * @param elder
     */
    private CheckIn saveCheckIn(CheckInApplyDto checkInApplyDto, Elder elder){
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0);

        this.save(checkIn);
        return checkIn;
    }

    /**
     * 第二个私有方法,新增签约办理
     *
     * @param checkInApplyDto
     * @param elder
     */
    private void saveContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        // 获取前端传递过来的合同相关对象
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto, contract);

        // 生成合同编号
        String contractNumber ="HT" + CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNumber);//获取合同编号
        contract.setElderId(Integer.valueOf(elder.getId()+ ""));
        contract.setElderName(elder.getName());
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        boolean flag = startDate.isBefore(LocalDateTime.now());//判断入住时间是否在当前时间之前
        contract.setStatus(flag? 1: 0);//0: 未生效, 1: 已生效, 2: 已过期, 3: 已失效 TODO
        contractMapper.insert( contract);
    }

    /*
     * 私有方法,新增或更新老人表
     *
     * @param checkInApplyDto
     * @param bed
     */
    private Elder saveOrUpdateElder(CheckInApplyDto checkInApplyDto , Bed bed) {
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        Elder newElder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, newElder);
        newElder.setStatus(1);
        newElder.setBedId(bed.getId());
        newElder.setBedNumber(bed.getBedNumber());

        // 判断老人信息是否已经存在
        //Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo()));
        Elder oldElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .ne(Elder::getStatus, 1));
        if (oldElder != null){
            elderMapper.updateById(newElder);
        }else {
            elderMapper.insert(newElder);
        }
        return newElder;
    }

    @Override
    public CheckInDetailVo detail(Long id) {
        // 查询入住信息
        // 查询老人信息
        // 查询合同
        // 查询入住配置
        // 转换家属列表
        // 整合数据返回

        // 查询入住信息
        CheckIn checkIn = getById(id);
        if (checkIn == null) {
            throw new BaseException("入住信息不存在");
        }

        // 查询老人信息
        Elder elder = elderMapper.selectById(checkIn.getElderId());

        // 查询合同
        LambdaQueryWrapper<Contract> contractQueryWrapper = new LambdaQueryWrapper<>();
        contractQueryWrapper.eq(Contract::getElderId, elder.getId());
        Contract contract = contractMapper.selectOne(contractQueryWrapper);

        // 查询入住配置
        LambdaQueryWrapper<CheckInConfig> configQueryWrapper = new LambdaQueryWrapper<>();
        configQueryWrapper.eq(CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(configQueryWrapper);

        // 转换家属列表
        List<ElderFamilyVo> elderFamilyVoList = null;
        if (checkIn.getRemark() != null && !checkIn.getRemark().isEmpty()) {
            try {
                // 将JSON字符串转换为ElderFamilyDto列表，再转换为ElderFamilyVo列表
                List<ElderFamilyDto> elderFamilyDtoList = JSONUtil.toList(JSONUtil.parseArray(checkIn.getRemark()), ElderFamilyDto.class);
                elderFamilyVoList = elderFamilyDtoList.stream().map(dto -> {
                    ElderFamilyVo vo = new ElderFamilyVo();
                    BeanUtils.copyProperties(dto, vo);
                    return vo;
                }).collect(Collectors.toList());
            } catch (Exception e) {
                // 如果转换失败，记录日志但不中断流程
                log.warn("家属信息转换失败: {}");
            }
        }

        // 整合数据返回
        CheckInDetailVo detailVo = new CheckInDetailVo();

        // 转换老人信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        if (elder != null) {
            BeanUtils.copyProperties(elder, checkInElderVo);
            if (elder.getBirthday() != null) {
                checkInElderVo.setBirthday(elder.getBirthday().toString());
            }
        }
        detailVo.setCheckInElderVo(checkInElderVo);

        // 设置家属信息
        detailVo.setElderFamilyVoList(elderFamilyVoList);

        // 转换入住配置信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        if (checkInConfig != null) {
            BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
            // 设置入住开始和结束时间
            checkInConfigVo.setStartDate(checkIn.getStartDate());
            checkInConfigVo.setEndDate(checkIn.getEndDate());
            checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        }
        detailVo.setCheckInConfigVo(checkInConfigVo);

        // 设置合同信息
        detailVo.setContract(contract);

        return detailVo;
    }

}
